var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var WxParse = require('../../utils/wxParse/wxParse.js');
var wxUtil = require('../../utils/wxUtil.js');
var app = getApp();
// pages/cart/cart.js
Page({
    /**
     * 页面的初始数据
     */
    data: {
        dataLoaded: false,
        isAllSelected: true,
        allTotalPrice: 0,
        cartList: [],
        cardId: '',
        cid: '',
        num: '',
        today: '',
        radioItems: [
            { name: '男', value: '1', checked: false },
            { name: '女', value: '2', checked: true }
        ],
        name: '',
        sex: '',
        birthday: '',
        password: '',
        passwordAgain: '',
        rechargeNum: '',
        leastMoney: '',
        userCard: [],
        haveCard: false,
        ModifyPsd: false,
        payNum: '',
        ty: '',
        oldPasswd: '',
        newPasswd: '',
        rechargeActual: '',
        payActual: '',
        orderId: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            cardId: options.cardId,
            leastMoney: options.leastMoney,
            ty: options.ty
        });
        this.getToday();
        this.getMembershipCard();
    },
    /**
     *监听日期切换
     */
    bindDateChange: function(e) {
        this.setData({
            birthday: e.detail.value
        })
    },
    /**
     *监听性别切换
     */
    radioChange: function(e) {
        var radioItems = this.data.radioItems;
        for (var i = 0, len = radioItems.length; i < len; ++i) {
            radioItems[i].checked = radioItems[i].value == e.detail.value;
            if (radioItems[i].checked) {
                this.setData({
                    sex: radioItems[i].value
                })
            }
        }
        this.setData({
            radioItems: radioItems
        })
    },
    /**
     * 监听姓名输入
     */
    listenerNameInput: function(e) {
        this.setData({
            name: e.detail.value
        })
    },
    /**
     * 监听密码输入
     */
    listenerPasswordInput: function(e) {
        this.setData({
            password: e.detail.value
        })
    },
    /**
     * 监听再次密码输入
     */
    listenerPasswordAgainInput: function(e) {
        this.setData({
            passwordAgain: e.detail.value
        })
    },
    /**
     * 监听原密码输入
     */
    listenerOldPsdInput: function(e) {
        this.setData({
            oldPasswd: e.detail.value
        })
    },
    /**
     * 监听新密码输入
     */
    listenerNewPsdInput: function(e) {
        this.setData({
            newPasswd: e.detail.value
        })
    },
    /**
     *  监听充值输入
     */
    listenerRechargeInput: function(e) {
        var _self = this;
        var userCard = this.data.userCard;
        var rechargeActual = this.data.rechargeActual;
        _self.setData({
            rechargeNum: e.detail.value
        })
        userCard.forEach(function(item) {
            var rechargeNum = _self.data.rechargeNum;
            rechargeActual = (item.rechargeNum * rechargeNum).toFixed(2);
            if (rechargeNum.length > 1 && (rechargeNum[0] == 0 || rechargeNum[0] == '.') && rechargeNum[1] != '.') {
                rechargeActual = '您输入的金额格式不符合要求'
            }
            if (rechargeActual === 'NaN') {
                rechargeActual = '您输入的金额不是数字'
            }
        })
        _self.setData({
            rechargeActual: rechargeActual
        })
    },
    /**
     *  监听付款金额输入
     */
    listenerPayInput: function(e) {
        var _self = this;
        var userCard = this.data.userCard;
        var payActual = this.data.payActual;
        this.setData({
            payNum: e.detail.value
        })
        userCard.forEach(function(item) {
            var payNum = _self.data.payNum;
            payActual = (payNum * item.discount / 10).toFixed(2);
            if (payNum.length > 1 && (payNum[0] == 0 || payNum[0] == '.') && payNum[1] != '.') {
                payActual = '您输入的金额格式不符合要求'
            }
            if (payActual === 'NaN') {
                payActual = '您输入的金额不是数字'
            }
        })
        _self.setData({
            payActual: payActual
        })
    },
    /**
     *申请会员卡
     */
    _applyOpening: function(evt) {
        var _self = this;
        var formId = evt.detail.formId;
        var cardId = this.data.cardId;
        var name = this.data.name;
        var sex = this.data.sex;
        var birthday = this.data.birthday;
        var password = this.data.password;
        var passwordAgain = this.data.passwordAgain;
        var reg = /^\d{6}$/;
        if (!name || name.length <= 0) {
            _self.showToast('您的姓名不能为空');
            return false;
        }
        if (!birthday) {
            _self.showToast('请选择您的生日');
            return false;
        }
        if (!password) {
            _self.showToast('请输入您的付款密码');
            return false;
        } else if (password.length < 6 || !reg.test(password)) {
            _self.showToast('付款密码必须为6位数字');
            return false;
        }
        if (!passwordAgain) {
            _self.showToast('请再次输入您的付款密码');
            return false;
        }
        if (password != passwordAgain) {
            _self.showToast('两次密码输入不一致');
            return false;
        };
        _self.setData({
            dataLoaded: false
        })
        ajax.P(
            '/openapi/CUser/createUserCard', {
                cardId: cardId,
                name: name,
                sex: sex || 2,
                password: password,
                birthday: birthday
            },
            function(data) {
                _self.setData({
                    dataLoaded: true
                })
                _self.showToast('申请成功', '', function() {
                    wx.navigateBack({
                        delta: 1
                    })
                });
            },
            function(data) {
                _self.setData({
                    dataLoaded: true
                })
            }
        );
        common.submitForm(formId);
    },
    /**
     * 充值
     */
    _getrechargeNum: function(evt) {
        var _self = this;
        var formId = evt.detail.formId;
        var cardId = this.data.cardId;
        var userCard = this.data.userCard;
        var rechargeNum = this.data.rechargeNum;
        var leastMoney = "";
        var reg = /^\d+(\.\d+)?$/;
        userCard.forEach(function(item) {
            leastMoney = item.leastMoney;
        })

        if (!rechargeNum) {
            _self.showToast('充值金额不能为空');
            return false;
        }
        if (!reg.test(rechargeNum)) {
            _self.showToast('付款金额输入有误');
            return false;
        }
        // if (rechargeNum == 0) {
        //     _self.showToast('您输入的金额必须大于0元');
        //     return false;
        // }
        if (rechargeNum.length > 1 && (rechargeNum[0] == 0 || rechargeNum[0] == '.') && rechargeNum[1] != '.') {
            _self.showToast('您输入的金额格式不符合要求');
            return false;
        }
        if (Number(rechargeNum) < Number(leastMoney)) {
            _self.showToast('充值金额不能小于起充金额');
            return false;
        }
        _self.setData({
            dataLoaded: false
        })
        ajax.P('/openapi/CUser/cardRecharge', {
                cardId: cardId,
                money: rechargeNum
            },
            function(data) {
                _self.setData({
                    dataLoaded: true
                })
                var wxPayParams = JSON.parse(data.result.wxPayParams);
                _self._package = wxPayParams.package;
                console.log(wxPayParams);
                var prepayArr = _self._package.split('=');
                common.submitPrepay(prepayArr[1]);
                _self._paySuccess(wxPayParams);
            },
            function(data) {
                _self.setData({
                    dataLoaded: true
                })
            }
        )
        common.submitForm(formId);
    },
    /**
     * 付款
     */
    _getPayNum: function(evt) {

        var _self = this;
        var cardId = this.data.cardId;
        var formId = evt.detail.formId;
        // var userCard = this.data.userCard;
        var password = this.data.password;
        var payNum = this.data.payNum;
        var reg = /^\d+(\.\d+)?$/;
        if (!payNum) {
            _self.showToast('付款金额不能为空');
            return false;
        }
        if (!reg.test(payNum)) {
            _self.showToast('付款金额输入有误');
            return false;
        }
        if (payNum.length > 1 && (payNum[0] == 0 || payNum == '.') && payNum[1] != '.') {
            _self.showToast('您输入的金额格式不符合要求');
            return false;
        }
        // if (payNum == 0) {
        //     _self.showToast('您输入的金额必须大于0元');
        //     return false;
        // }
        if (!password) {
            _self.showToast('支付密码不能为空');
            return false;
        }
        _self.setData({
            dataLoaded: false
        })
        ajax.P('/openapi/CUser/cardPay', {
                cardId: cardId,
                money: payNum,
                password: password
            },
            function(data) {
                _self.setData({
                    dataLoaded: true
                })
                _self.showToast('付款成功', '', function() {
                    wx.navigateBack({
                        delta: 1
                    })
                });
            },
            function(data) {
                _self.setData({
                    dataLoaded: true
                })
            }
        );
        common.submitForm(formId);
    },
    /**
     * 支付成功回调
     */
    _paySuccess(wxPayParams) {
        var _self = this;
        wxPayParams.success = function() {
            _self.showToast('充值成功', '', function() {
                wx.navigateBack({
                    delta: 1
                })
            });
        }
        wxUtil.wxPay(wxPayParams);
    },
    /**
     * 修改密码
     */
    _ModifyPsd: function(evt) {
        var _self = this;
        var oldPasswd = this.data.oldPasswd;
        var newPasswd = this.data.newPasswd;
        var formId = evt.detail.formId;
        if (oldPasswd.length < 6) {
            _self.showToast('请输入您的6位原密码');
            return false;
        }
        if (newPasswd.length < 6) {
            _self.showToast('请输入您的6位新密码');
            return false;
        }
        _self.setData({
            dataLoaded: false
        })
        ajax.P('/openapi/CUser/modifyPassword', {
                oldPasswd: oldPasswd,
                newPasswd: newPasswd
            },
            function(data) {
                _self.setData({
                    dataLoaded: true
                })
                _self.showToast('修改成功', '', function() {
                    _self.setData({
                        ModifyPsd: false,
                        oldPasswd: '',
                        newPasswd: ''
                    })
                });
            },
            function(data) {
                _self.setData({
                    dataLoaded: true
                })
            }
        )
        common.submitForm(formId);
    },
    /**
     * 跳转修改密码
     */
    _slectModifyPsd: function(evt) {
        var formId = evt.detail.formId;
        this.setData({
            ModifyPsd: true
        })
        common.submitForm(formId);
    },
    /**
     *获取会员卡信息
     */
    getMembershipCard: function() {
        var _self = this;
        ajax.P('/openapi/CUser/userCard', {},
            function(data) {

                var data = data.result;

                if (data.userCard) {
                    data.userCard.forEach(function(item, index) {
                        var cid = _self.PrefixInteger(item['cid'], 6);
                        item['cid'] = cid;
                    })
                }
                _self.setData({
                    cardList: data.cardList,
                    userCard: data.userCard,
                    haveCard: data.haveCard,
                    dataLoaded: true
                })


            })
    },
    /**
     * 会员卡编号
     */
    PrefixInteger: function(num, length) {
        return (Array(length).join('0') + num).slice(-length);
    },
    /**
     * 展示模态tip
     */
    showToast(title, timeout, callBack) {
        var toast = this.data.toast || {};
        clearTimeout(toast.timer);

        // 弹层设置~
        toast = {
            show: true,
            title
        };
        this.setData({
            toast
        });

        var timer = setTimeout(() => {
            this.clearToast();
            callBack && callBack();
        }, timeout || 2000);

        this.setData({
            'toast.timer': timer
        });
    },
    /**
     * 关闭模态tip
     */

    clearToast() {
        var toast = this.data.toast || {};
        clearTimeout(toast.timer);

        this.setData({
            'toast.show': false
        });
    },
    /**
     * 获取当前日期
     */
    getToday: function() {
        var today = new Date();
        var formatDate = function(date) {
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '-' + m + '-' + d;
        };

        this.setData({
            today: formatDate(today)
        })
    },
    _jump:function(evt){
        common.jump(evt);
    }
})